﻿using MediatR;
using S.Common.ApiResult;
using S.PregnancyTest.Domain.Model;
using S.PregnancyTest.Infrastructure.Interface;
using S.PregnancyTest.Read.API.Application.Command;

namespace S.PregnancyTest.Read.API.Application.CommandHandlers
{
    public class GetPregnancyTestListHandler : IRequestHandler<GetPregnancyTestListCommand, ApiResult<List<PregnancyTestModel>>>
    {

        private readonly IPregnancyTestRepository repository;

        public GetPregnancyTestListHandler(IPregnancyTestRepository repository)
        {
            this.repository = repository;
        }

        public async Task<ApiResult<List<PregnancyTestModel>>> Handle(GetPregnancyTestListCommand request, CancellationToken cancellationToken)
        {
            var list = await repository.GetAllAsync();

            //查询条件
            if (!string.IsNullOrWhiteSpace(request.StateDate) && !string.IsNullOrWhiteSpace(request.EndDate))
            {
                list = list.Where(x => x.PregnancyDate > Convert.ToDateTime(request.StateDate) && x.PregnancyDate <= Convert.ToDateTime(request.EndDate).AddDays(1)).ToList();
            }
            if (!string.IsNullOrWhiteSpace(request.MonthEITag))
            {
                list = list.Where(x => x.EarTag.Contains(request.MonthEITag)).ToList();
            }
            if (request.UserId != 0)
            {
                list = list.Where(x => x.UserId == request.UserId).ToList();
            }
            if (request.PregnancytestResult != 0)
            {
                list = list.Where(x => x.PregnancytestResult == request.PregnancytestResult).ToList();
            }
            if (request.ParityNumber != 0)
            {
                list = list.Where(x => x.ParityNumber == request.ParityNumber).ToList();
            }

            ApiResult<List<PregnancyTestModel>> result = new ApiResult<List<PregnancyTestModel>>();

            //总页数、总条数
            int totalCount = list.Count;
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);

            result.totalCount = totalCount;
            result.pageCount = pageCount;

            // 对列表进行分页处理
            result.Data = list.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).OrderByDescending(x => x.CreateDate).ToList();

            return result;
        }
    }
}
